package PhraseCount;
import Snowball.*;
import MailLogger.*;
//import Combination.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Vector;
import java.util.HashSet;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class PhraseCount extends Configured implements Tool {
  public static class MapClass extends MapReduceBase
    implements Mapper<LongWritable, Text, Text, Text> {

    private Text text = new Text();
    private Text text2 = new Text();
    
    private Class stemClass;
    private SnowballStemmer stemmer;
    private MailLogger l = new MailLogger("chintown@gmail.com");
    
    public void map(LongWritable key, 
                    Text value,
                    OutputCollector<Text, Text> output,
                    Reporter reporter) throws IOException {
      Pattern legalChar = Pattern.compile("[\\p{Space}\\p{Graph}]+");
      Matcher m;

      String line = value.toString().toLowerCase();
      StringTokenizer itr = new StringTokenizer(line,"\t");
      String token = "";

      Vector<String> validTerms;
      String validTerm = "";
      String validAssociatedTerm = "";
      String validAssociatedTerm2 = "";
      
      for (int i=0; i<2; i++) {
        token = itr.nextToken();
        if (i == 1) {
          m = legalChar.matcher(token);
          if (!m.matches()) { //the line contains some non-US-ASCII characters, skip this line!
            continue;
          }

          validTerms = this.customizedTokenizer(token,reporter);
          
          // for (int j=0; j<validTerms.size(); j++) {
            // validTerm = (String)validTerms.get(j);
            // text.set(validTerm);
            // for (int k=0; k<validTerms.size(); k++) {
              // validAssociatedTerm = (String)validTerms.get(k);
              // text2.set(validAssociatedTerm);
              // output.collect(text, text2);
            // }
          // }
          
          for (int j=0; j<validTerms.size(); j++) {
            validTerm = (String)validTerms.get(j);
            text.set(validTerm);
            for (int k=0; k<validTerms.size()-1; k++) {
              validAssociatedTerm = (String)validTerms.get(k);
              validAssociatedTerm2 = (String)validTerms.get(k+1);
              text2.set(validAssociatedTerm+" "+validAssociatedTerm2);
              output.collect(text, text2);
              //reporter.setStatus(text+"-"+text2);
            }
          }
          
          break;
        }
      }
    }
    private Vector<String> customizedTokenizer(String qry, Reporter reporter) {
      Vector<String> finalValidTerms = new Vector<String>();
      HashSet<String> uniqueTerms;
      Vector<String> validTerms = new Vector<String>();
      String term;
      String validTerm;
      
      try {
        stemClass = Class.forName("Snowball.englishStemmer");
        stemmer = (SnowballStemmer) stemClass.newInstance();
      } catch (Exception e) {
      }
      
      String regexUrl = "(http|https://)?[\\w-]+[.][\\w-]+([.][\\w^_]+){0,3}((/[\\S]+)+)?";
      qry = qry.replaceAll(regexUrl, "");
      
      StringTokenizer itr2 = new StringTokenizer(qry, " .,:;@?!<>()[]{}=+*|/\\");
      while (itr2.hasMoreTokens()) {
        term = this.lengthFilter(itr2.nextToken(),reporter);
        if (term.equals("")) {
          continue;
        }
        else if (term.indexOf("%") >= 0) {
          validTerms.addAll(symbolPercentageTokenizer(term,reporter));
        }
        else {
          if (!term.equals("")) {
            validTerms.add(term);
          }
        }
      }
      String x = "";
      uniqueTerms = new HashSet<String>();
      for (int j=0; j<validTerms.size(); j++) {
        x = validTerm = validTerms.get(j);
        validTerm = this.trimMore(validTerm,'"'+"`'~#&_-^"+" .,:;@?!<>()[]{}=+*|/\\",reporter);
        validTerm = this.lengthFilter(validTerm,reporter);
        stemmer.setCurrent(validTerm);
        stemmer.stem();
        validTerm = stemmer.getCurrent();
        validTerm = this.trimMore(validTerm,'"'+"`'~#&_-^"+" .,:;@?!<>()[]{}=+*|/\\",reporter);
        validTerm = this.lengthFilter(validTerm,reporter);
        if ( (!validTerm.equals("")) && (!uniqueTerms.contains(validTerm)) ) {
          // if (validTerm.equals("google")) {
            // reporter.setStatus(x+"=>google");
          // }
          uniqueTerms.add(validTerm);
          finalValidTerms.add(validTerm);
        }
      }
      return finalValidTerms;
    }
    private String lengthFilter(String s, Reporter reporter) {
      if ( (s.length() < 2) || (s.length() > 20) ) {
        return "";
      } else {
        return s;
      }
    }
    private Vector<String> symbolPercentageTokenizer(String s, Reporter reporter) {
      Vector<String> validTerms = new Vector<String>();
      if (s.indexOf("%") >= 0) {
        validTerms.add(s.substring(0,s.indexOf("%")+1));
        validTerms.addAll(symbolPercentageTokenizer(s.substring(s.indexOf("%")+1),reporter));
      }
      else {
        if (!s.equals("")) {
          validTerms.add(s);
        }
      }
      return validTerms;
    }
    private String trimMore(String s, String list, Reporter reporter) {
      boolean is_clean = true;
      if (s.equals("")) {
        return "";
      }
      if (list.indexOf(s.charAt(0)) >= 0) {
        s = s.substring(1);
        is_clean = false;
      }

      if (s.equals("")) {
        return "";
      }
      if (list.indexOf(s.charAt(s.length()-1)) >= 0) {
        s = s.substring(0,s.length()-1);
        is_clean = false;
      }

      if (is_clean == false) {
        s = this.trimMore(s, list, reporter);
      }
      else {
        return s;
      }
      return s;
    }
  }

  public static class Reduce extends MapReduceBase
    implements Reducer<Text, Text, Text, Text> {
    
    private Text text = new Text();
    
    public void reduce(Text key, 
                       Iterator<Text> values,
                       OutputCollector<Text, Text> output,
                       Reporter reporter) throws IOException {
      String associatedTerms = "";
      while (values.hasNext()) {
        associatedTerms += values.next()+",";
      }
      if (associatedTerms.length() > 1) {
        associatedTerms = associatedTerms.substring(0,associatedTerms.length()-1);
      }
      text.set(associatedTerms);
      output.collect(key, text);
    }
  }

  public int run(String[] args) throws Exception {
    JobConf conf = new JobConf(getConf(), PhraseCount.class);
    conf.setJobName("PhraseCount");

    conf.setMapperClass(MapClass.class);
    //conf.setCombinerClass(Reduce.class);
    conf.setReducerClass(Reduce.class);

    FileInputFormat.setInputPaths(conf, (String)args[0]);
    FileOutputFormat.setOutputPath(conf, new Path((String)args[1]));

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat(TextOutputFormat.class);

    conf.setOutputKeyClass(Text.class);
    conf.setOutputValueClass(Text.class);
    
    //conf.setNumMapTasks(15);
    //conf.setNumReduceTasks(1);
    
    JobClient.runJob(conf);
    return 0;
  }


  public static void main(String[] args) throws Exception {
    int res = ToolRunner.run(new Configuration(), new PhraseCount(), args);
    System.exit(res);
  }
}
